package com.finalterm.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.finalterm.common.constant.Constants;
import com.finalterm.common.result.Result;
import com.finalterm.order.dto.OrderCreateDTO;
import com.finalterm.order.service.OrderService;
import com.finalterm.order.vo.OrderVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 订单控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/order")
@RequiredArgsConstructor
public class OrderController {
    
    private final OrderService orderService;
    
    /**
     * 创建订单
     */
    @PostMapping("/create")
    @SentinelResource(value = "order-create", fallback = "createOrderFallback")
    public Result<OrderVO> createOrder(@RequestHeader("X-User-Id") Long userId,
                                     @Validated @RequestBody OrderCreateDTO createDTO) {
        OrderVO orderVO = orderService.createOrder(userId, createDTO);
        return Result.success("订单创建成功", orderVO);
    }
    
    /**
     * 创建订单降级方法
     */
    public Result<OrderVO> createOrderFallback(Long userId, OrderCreateDTO createDTO, Throwable ex) {
        log.warn("创建订单降级，userId: {}, 异常: {}", userId, ex.getMessage());
        return Result.error("订单创建失败，请稍后重试");
    }
    
    /**
     * 获取订单详情
     */
    @GetMapping("/detail/{orderId}")
    @SentinelResource(value = "order-detail")
    public Result<OrderVO> getOrderDetail(@PathVariable Long orderId) {
        OrderVO orderVO = orderService.getOrderById(orderId);
        return Result.success(orderVO);
    }
    
    /**
     * 根据订单号获取订单
     */
    @GetMapping("/orderNo/{orderNo}")
    @SentinelResource(value = "order-by-no")
    public Result<OrderVO> getOrderByOrderNo(@PathVariable String orderNo) {
        OrderVO orderVO = orderService.getOrderByOrderNo(orderNo);
        return Result.success(orderVO);
    }
    
    /**
     * 分页查询用户订单
     */
    @GetMapping("/list")
    @SentinelResource(value = "order-list")
    public Result<Page<OrderVO>> getUserOrders(@RequestHeader("X-User-Id") Long userId,
                                             @RequestParam(defaultValue = "1") int page,
                                             @RequestParam(defaultValue = "10") int size) {
        Page<OrderVO> orderPage = orderService.getUserOrders(userId, page, size);
        return Result.success(orderPage);
    }
    
    /**
     * 更新订单状态（内部调用）
     */
    @PutMapping("/status")
    @SentinelResource(value = "order-status-update")
    public Result<Boolean> updateOrderStatus(@RequestParam String orderNo,
                                           @RequestParam String status) {
        boolean success = orderService.updateOrderStatus(orderNo, status);
        return Result.success(success);
    }
    
    /**
     * 取消订单
     */
    @PutMapping("/cancel/{orderNo}")
    @SentinelResource(value = "order-cancel")
    public Result<Boolean> cancelOrder(@PathVariable String orderNo) {
        boolean success = orderService.cancelOrder(orderNo);
        return Result.success("订单取消成功", success);
    }

    /**
     * 更新订单支付状态（支付服务调用）
     */
    @PostMapping("/updatePaymentStatus/{orderNo}")
    @SentinelResource(value = "order-payment-status-update")
    public Result<Boolean> updatePaymentStatus(@PathVariable String orderNo) {
        boolean success = orderService.updateOrderStatus(orderNo, Constants.ORDER_STATUS_PAID);
        return Result.success(success);
    }

    /**
     * 根据订单号获取订单信息（支付服务调用）
     */
    @PostMapping("/getByOrderNo/{orderNo}")
    @SentinelResource(value = "order-get-by-no")
    public Result<Object> getOrderByOrderNoForPayment(@PathVariable String orderNo) {
        OrderVO orderVO = orderService.getOrderByOrderNo(orderNo);
        return Result.success(orderVO);
    }
}
